package utils

import (
	"log/slog"
	"strconv"

	"github.com/beevik/etree"
)

func GetXmlElementText(doc *etree.Document, path string) string {
	var element = doc.FindElement(path)
	if element != nil {
		return element.Text()
	} else {
		return ""
	}
}

func GetXmlElementInt64(doc *etree.Document, path string) int64 {
	var str = GetXmlElementText(doc, path)
	if len(str) > 0 {
		value, err := strconv.ParseInt(str, 10, 64)
		if err != nil {
			slog.Error(err.Error())
			return 0
		}
		return value
	} else {
		return 0
	}
}

func GetXmlElementInt(doc *etree.Document, path string) int {
	return int(GetXmlElementInt64(doc, path))
}

func GetXmlElementTextArray(doc *etree.Document, path string) []string {
	var arr = make([]string, 0)
	var elements = doc.FindElements(path)
	if elements != nil && len(elements) > 0 {
		for i := range elements {
			arr = append(arr, elements[i].Text())
		}
	}
	return arr
}

func GetXmlElementInt64Array(doc *etree.Document, path string) []int64 {
	var strArr = GetXmlElementTextArray(doc, path)
	var intArr = make([]int64, 0)
	for i := range strArr {
		value, err := strconv.ParseInt(strArr[i], 10, 64)
		if err != nil {
			slog.Error(err.Error())
		}
		intArr = append(intArr, value)
	}
	return intArr
}

func GetXmlElementIntArray(doc *etree.Document, path string) []int {
	var strArr = GetXmlElementTextArray(doc, path)
	var intArr = make([]int, 0)
	for i := range strArr {
		value, err := strconv.ParseInt(strArr[i], 10, 64)
		if err != nil {
			slog.Error(err.Error())
		}
		intArr = append(intArr, int(value))
	}
	return intArr
}
